$(document).ready(function () {
    let table = $('#ordersTable').DataTable({
        "fnPreDrawCallback": function (oSettings) {
            var processing_div = $('#ordersTable_processing');
            processing_div.removeClass("card");
            processing_div.addClass("align-middle");

        },
        "ajax": {
            url: "/api/orders/",
            type: "GET",
        },
        "ordering": false,
        "serverSide": true,
        "lengthChange": false,
        "searching": true,
        "bProcessing": true,
        "dom": "<'row'<'col-sm-12 col-md-12'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        "language": {
            "sSearch": "",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "没有数据！",
            "sEmptyTable": "当前未查询到订货信息",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmpty": "显示0到0条记录",
            "sInfoFiltered": "数据表中共有 _MAX_ 条记录",
            "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                '<span class="sr-only">Loading...</span>',
            "sLoadingRecords": '',
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"

            }
        },
        "columns": [
            {
                data: {
                    fields: 'fields'
                },
                sDefaultContent: "-",
                "render": function (data) {
                    return data['fields']['product_item_num'] + '-' + data['fields']['sub_item_num'];
                }
            },
            {
                data: {
                    fields: 'fields'
                },
                sDefaultContent: "-",
                "render": function (data) {
                    return data['fields']['flavor'] + '/' + data['fields']['unit'];
                }
            },
            {
                data: 'fields.product_type',
                sDefaultContent: "-"
            },
            {
                data: {
                    fields: 'fields',
                },
                width: "8%",
                "render": function (data) {
                    let order_id = data['pk'],
                        product_item_num = Base64.encode(data['fields']['product_item_num']),
                        sub_item_num = Base64.encode(data['fields']['sub_item_num']),
                        flavor = Base64.encode(data['fields']['flavor']),
                        unit = Base64.encode(data['fields']['unit']),
                        product_type = Base64.encode(data['fields']['product_type']),

                    action = '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#editOrder" onclick="edit_order_modal(\'' + order_id + '\',\'' + product_item_num + '\',\'' + sub_item_num + '\',\'' + flavor + '\',\'' + unit + '\',\'' + product_type + '\')">编辑</a>\n' +
                        '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#deleteOrder" onclick="delete_order_modal(\'' + order_id + '\',\'' + product_item_num + '\',\'' + sub_item_num + '\',\'' + product_type + '\')">删除</a>\n';
                    return '<a href="javascript:void(0);"  id="ctl-dropdownMenuLink" data-toggle="dropdown" data-flip="false" aria-haspopup="true" aria-expanded="true">更多</a>\n' +
                        '<div class="dropdown-menu" data-flip="false" aria-labelledby="ctl-dropdownMenuLink">\n' +
                        action +
                        '</div>'
                }
            }
        ]
    });
    $('.dataTables_filter').attr("hidden", "hidden");

});

function delete_order_modal(order_id,product_item_num,sub_item_num,product_type) {
    $('#delete_order_id').text(order_id);
    $('#delete_product_item_num').text(Base64.decode(product_item_num)+"-"+Base64.decode(sub_item_num));
    $('#delete_product_type').text(Base64.decode(product_type));
}

function delete_order() {
    const order_id = $('#delete_order_id').text();
    $.ajax({
            url: "/api/orders/" + order_id + "/",
            async: true,
            type: "DELETE",
            contentType: "application/json; charset=utf-8",
            success: function (data) {   // success callback function
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>订货信息删除成功！</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
                $("#deleteOrder").modal('hide');
                refresh_table();
            },
            error: function (result) {
                $("#deleteProduct").modal('hide');
                if (result['status'] === 403) {
                    alert("403！你没有权限操作！")
                } else {
                    alert(result['status'] + "," + result['statusText'])
                }
            },
            // dataType: "json" //返回值类型
        }
    );
}

function edit_order_modal(order_id,product_item_num,sub_item_num,flavor,unit,product_type) {
    $('#edit_order_id').val(order_id);
    $('#edit_product_item_num').val(Base64.decode(product_item_num));
    $('#edit_product_sub_item_num').val(Base64.decode(sub_item_num));
    $('#edit_order_flavor').val(Base64.decode(flavor));
    $('#edit_order_unit').val(Base64.decode(unit));
    $('#edit_product_type').val(Base64.decode(product_type));
}

function edit_order() {
    let check_valid,
        selector_Id;
    check_valid = check_form("addOrder");
    if (check_valid) {
        selector_Id = check_valid.id;
        $('#' + selector_Id + '').css('border', 'solid 2px #ff0000');
        setTimeout(remove_css, 1000);
    } else {
        let edit_order_id = $('#edit_order_id').val(),
            edit_product_item_num = $('#edit_product_item_num').val(),
            edit_product_sub_item_num = $('#edit_product_sub_item_num').val(),
            edit_order_flavor = $('#edit_order_flavor').val(),
            edit_order_unit = $('#edit_order_unit').val(),
            edit_product_type = $('#edit_product_type').val();
        $.ajax({
            url: "/api/orders/"+edit_order_id+"/",
            async: true,
            type: "PUT",
            data: JSON.stringify({
                product_item_num: edit_product_item_num,
                sub_item_num: edit_product_sub_item_num,
                flavor: edit_order_flavor,
                unit: edit_order_unit,
                product_type: edit_product_type
            }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {   // success callback function
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>订货信息添加成功！</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
                $("#editOrder").modal('hide');
                refresh_table();
            },
            error: function (result) {
                $("#editOrder").modal('hide');
                if (result['status'] === 403) {
                    alert("403！你没有权限操作！")
                } else {
                    alert(result['status'] + "," + result['statusText'])
                }
            },
            // dataType: "json" //返回值类型
        })
    }


}

function refresh_table() {
    let table = $('#ordersTable').DataTable();
    table.ajax.reload();
}

function filter_orders() {
    const filter_condition = $('#filter_condition').val(),
        filter_content = "query" + "=" + filter_condition,
        table = $('#ordersTable').DataTable();
    table.search(filter_content).draw();
}

$(document).keyup(function (event) {
    if (event.keyCode === 13) {
        filter_orders();
    }
});

function check_form(id) {
    /**判断是否有选项为空
     * **/
    let result = '',
        element = $('#'+id+'');

    element.find('[required]').each(
        function () {
            let fieldElement = $(this);
            //如果为null则设置为''
            let value = fieldElement.val() || '';
            // console.log(this);
            if (value) {
                if (Array.isArray(value)) {
                    if (value.length === 0 ) {
                       value = false
                    }
                } else {
                    value = value.trim();
                }
            }

            if (!value) {
                result = this;
                return result;
            }
        }
    );
    return result;
}

function remove_css() {
    $('[required]').css('border', '1px solid #d1d3e2')
}

function upload_file(type) {
    let form_data = new FormData();
    let file_info = $('#input_upload_file')[0].files[0];
    form_data.append('file', file_info);
    form_data.append('type',type)
    $.ajax({
        url: '/api/data_processor/upload/',
        type: 'POST',
        data: form_data,
        processData: false,  // tell jquery not to process the data
        contentType: false, // tell jquery not to set contentType
        success: function (callback) {
            $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>产品导入成功!</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
            $("#uploadFile").modal('hide');
            let table = $('#ordersTable').DataTable();
            let timesRun = 0;
            let start_interval = setInterval(function () {
                timesRun += 1;
                if (timesRun === 1) {
                    clearInterval(start_interval);
                }
                table.ajax.reload(null, false);
            }, 2000);
        },
        error: function (result) {
            $("#uploadFile").modal('hide');
            alert(result['responseJSON']['msg']);
        },
    });
}

function download_file(action) {
    let httpMethod = 'get';
    let url = "/api/data_processor/download?action="+action;
    $.fileDownload(url, {
        httpMethod: httpMethod,
        // 因为这个插件貌似只支持URL参数,所以要用jquery param将js对象转成URL参数
        prepareCallback: function (url) {
            console.log("正在导出...");
        },
        //要想成功回调失败和成功方法，要在响应首部加 response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        successCallback: function (url) {
            console.log("导出成功");
        },
        failCallback: function (html, url) {
            console.log("导出失败");
        }
    })
}